﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DAL;
using System.Data;
using DTO;
using BLL.Util;

namespace BLL
{
    public class CategoryBLL
    {
        /// <summary>
        /// 返回所有Category内容
        /// </summary>
        /// <param name="aid">用户ID</param>
        /// <returns></returns>
        internal static List<Category> GetMyAllCategory(string aid)
        {

            CategoryDAL dal = new CategoryDAL();
            var table = dal.GetCategoryTable(aid);
            List<Category> list = new List<Category>();
            foreach (DataRow row in table.Select("ParentID=0"))
            {
                var node = new Category() { ID = int.Parse(row["ID"].ToString()), Title = row["Title"].ToString() };
                node.Nodes = new List<Category>();
                foreach (var item in table.Select("ParentID="+node.ID))
                {
                    var sub = new Category() { ID = int.Parse(item["ID"].ToString()), Title = item["Title"].ToString(), Parent = node };
                    node.Nodes.Add(sub);
                }
                list.Add(node);
            }
            return list;           
        }
        /// <summary>
        /// 获取所有子类分类
        /// </summary>
        /// <param name="aid"></param>
        /// <returns></returns>
        private static List<Category> GetMyAllSubCategory(string aid)
        {
            List<Category> list = new List<Category>();
            foreach (var item in CacheHelper.GetMyAllCategory(aid))
            {
                list.AddRange(item.Nodes);
            }
            return list;
        }
        /// <summary>
        /// 获取分类项目实体
        /// </summary>
        /// <param name="aid"></param>
        /// <param name="cid"></param>
        /// <returns></returns>
        public static Category GetCategory(string aid, int cid)
        {
            return GetMyAllSubCategory(aid).Find(p => p.ID == cid);
        }
    }
}
